﻿using System.Collections.Generic;
using System.Linq;
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;

namespace AdministrationWeb.Administration
{
    /// <summary>
    /// Summary description for ShowMentorImage
    /// </summary>
    public class ShowMentorImage : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            Int32 mentorID;
            if (context.Request.QueryString["id"] != null)
                mentorID = Convert.ToInt32(context.Request.QueryString["id"]);
            else
                throw new ArgumentException("No parameter specified");

            context.Response.ContentType = "image/jpeg";
            Stream strm = ShowEmpImage(mentorID);
            byte[] buffer = new byte[1048576];
            int byteSeq = strm.Read(buffer, 0, 1048576);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 1048576);
            }
            //context.Response.BinaryWrite(buffer);
        }

        public Stream ShowEmpImage(int mentorID)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ApplicationConnectionString"].ConnectionString;
            MySqlConnection conn = new MySqlConnection(connectionString);
            string sql = "SELECT photo FROM mentor WHERE mentor_id=" + mentorID;
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.CommandType = CommandType.Text;
            
            try
            {
                conn.Open();
                object img = cmd.ExecuteScalar();
                return new MemoryStream((byte[])img);
            }
            catch
            {
                return null;
            }
            finally
            {
                conn.Close();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}